<!-- 模板界面,使用时全局替换
    user  为此页要维护的信息(例如department)
    userData 为此页面要维护的信息的数组(例如deptData) 
    userName    为此页面要维护的信息的一个成员(例如deptName之于department),作为示例使用
    -->
<template>
  <div>
    用户界面
    <el-button type="primary" plain @click="addButtonClicked">添加</el-button>
    <el-button type="primary" plain @click="batchRemoveButtonClicked">批量删除</el-button>
    <el-button type="primary" plain @click="queryButtonClicked">查询</el-button>
    <el-button type="primary" plain @click="queryResetButtonClicked">重置</el-button>
    <el-table :data="userData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column>
        <!-- <el-checkbox></el-checkbox> -->
        <el-table-column type="selection" width="55"></el-table-column>
      </el-table-column>
      <!-- <el-table-column prop="date" label="日期" width="180"></el-table-column> -->
      <el-table-column prop="userName" label="用户名" width="180"></el-table-column>
      <!-- 删除密码的显示 -->
      <!-- <el-table-column prop="passWord" label="密码" width="180"></el-table-column> -->
      <el-table-column prop="name" label="真实姓名" width="180"></el-table-column>
      <el-table-column prop="userTypeName" label="角色" width="180"></el-table-column>
      <el-table-column prop="departmentName" label="科室" width="180"></el-table-column>
      <el-table-column prop="jobTitleName" label="职称" width="180"></el-table-column>
      <!-- 其实在el-table下,书写的各个列的信息,然后会根据userData自动生成n行 -->
      <el-table-column align="right" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加和修改 -->
    <el-dialog title="添加" :visible.sync="addDialogVisible">
      <el-form :model="user" ref="form" label-width="100px">
        <el-form-item label="名字" prop="userName">
          <el-input v-model="user.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input type="password" v-model="user.passWord"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="user.name"></el-input>
        </el-form-item>
        <el-form-item label="科室" prop="name">
          <el-cascader
            v-model="tmpDepartments"
            :options="departments"
            :props="props"
            collapse-tags
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="用户类别" prop="usertype">
          <el-cascader v-model="tmpRoles" :options="roles" :props="props" collapse-tags clearable></el-cascader>
        </el-form-item>
        <el-form-item label="医生职称" prop="jobTitle">
          <el-select v-model="user.jobTitle" placeholder="请选择医生职称">
            <el-option
              v-for="item in doctorTitle"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否参与排班" prop="onDuty">
          <el-radio v-model="user.onDuty" label="0">不参与排班</el-radio>
          <el-radio v-model="user.onDuty" label="1">参与排班</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 筛选界面 -->
    <el-dialog title="筛选" :visible.sync="queryDialogVisible">
      <el-form :model="userQuery" ref="form" label-width="100px">
        <el-form-item label="名字" prop="userName">
          <el-input v-model="userQuery.userName"></el-input>
        </el-form-item>
        <!-- 筛选时不应该拿密码筛选 -->
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="userQuery.name"></el-input>
        </el-form-item>
        <el-form-item label="科室" prop="name">
          <el-cascader
            v-model="tmpQueryDepartments"
            :options="departments"
            :props="props"
            collapse-tags
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="用户类别" prop="usertype">
          <el-cascader
            v-model="tmpQueryRoles"
            :options="roles"
            :props="props"
            collapse-tags
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="医生职称" prop="usertype">
          <el-select v-model="userQuery.jobTitle" placeholder="请选择医生职称">
            <el-option
              v-for="item in doctorTitle"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否排班" prop="usertype">
          <el-radio v-model="userQuery.onDuty" label="0">不参与排班</el-radio>
          <el-radio v-model="userQuery.onDuty" label="1">参与排班</el-radio>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="queryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="queryConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <div class="block">
      <span class="demonstration">显示总数</span>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPageNum"
        :page-sizes="[1, 5, 10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRecord"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  insert,
  update,
  deleteElem,
  getPage,
  getAll,
  getAllType
} from "@/api/user.js";
import { getAll as getAllDepartment } from "@/api/department.js";
import { getAll as getAllRole } from "@/api/role.js";
export default {
  mounted() {
    // 渲染完成
    // 一定要先载入部门
    this.loadDepartments();
    this.loadPageData();
    this.loadRoles();
  },
  data() {
    return {
      // 科室复选框
      props: { multiple: true },
      // 全局复选框
      multipleSelection: [],
      // 分页
      pageSize: 5,
      totalRecord: 3,
      currentPageNum: 1,
      // 对话框
      addDialogVisible: false,
      queryDialogVisible: false,
      // 局部对象
      departments: [],
      roles: [],
      // 用于转换编号和名称的字典
      departmentDict: {},
      roleDict: {},
      doctorTitle: [
        { value: 0, label: "无" },
        { value: 1, label: "主任医师" },
        { value: 2, label: "副主任医师" },
        { value: 3, label: "主治医师" },
        { value: 4, label: "住院医师" }
      ],
      jobTitleDict: {
        0: "无",
        1: "主任医师",
        2: "副主任医师",
        3: "主治医师",
        4: "住院医师"
      },

      // 临时对象
      tmpDepartments: [],
      tmpRoles: [],
      tmpQueryDepartments: [],
      tmpQueryRoles: [],
      // 存储路径
      /* 补全信息 */
      user: {
        id: "",
        userName: "",
        passWord: "",
        name: "",
        department: [],
        userType: [],
        jobTitle: "",
        onDuty: ""
      },
      /* 补全信息 */
      userQuery: {
        id: "",
        userName: "",
        passWord: "",
        name: "",
        department: [],
        userType: [],
        jobTitle: "",
        onDuty: ""
      },
      // 对象数组
      userData: []
    };
  },
  methods: {
    addButtonClicked() {
      // 清空
      /* 补全信息 */
      this.user.id = "";
      this.user.userName = "";
      this.user.passWord = "";
      this.user.name = "";
      this.user.department = [];
      this.user.userType = [];
      this.user.jobTitle = "";
      this.user.onDuty = "";

      // 清空临时变量
      this.tmpDepartments = [];
      this.tmpRoles = [];

      this.updateFlag = false;
      this.addDialogVisible = true;
      this.loadPageData();
    },
    loadDepartments() {
      console.log("send getAllDepartment");
      getAllDepartment().then(response => {
        this.departments = [];
        if (response.data.code == 0) {
          response.data.data.forEach(item => {
            this.departments.push({ value: item.id, label: item.deptName });
            // 初始化这个字典
            this.departmentDict[item.id] = item.deptName;
          });
          console.log(this.departmentDict);
          // 这里似乎又出现了异步的问题,在此强制重新载入页面信息即可
          this.loadPageData();
        } else {
          console.log("getDepartment ERROR!!");
        }
      });
      // todo: 对接后删掉
      // this.departments = [
      //   { value: 1, label: "骨科" },
      //   { value: 2, label: "外科" },
      //   { value: 3, label: "儿科" }
      // ];
    },
    loadPageData() {
      // 这个函数会更新总个数和数组中的信息

      // 分离参数
      this.userQuery.department = [];
      this.tmpQueryDepartments.forEach(item => {
        this.userQuery.department.push(item[0]);
      });
      this.userQuery.userType = [];
      this.tmpQueryRoles.forEach(item => {
        this.userQuery.userType.push(item[0]);
      });
      this.userQuery.jobTitle = this.userQuery.jobTitle;
      // 查询条件
      let pageParam = {
        /* 补全信息 */
        username: this.userQuery.userName,
        password: this.userQuery.passWord,
        name: this.userQuery.name,
        department: this.userQuery.department,
        userType: this.userQuery.userType,
        jobTitle: this.userQuery.jobTitle,
        onDuty: this.userQuery.onDuty,
        currentPage: this.currentPageNum,
        pageSize: this.pageSize
      };
      console.log("user send getPage Param: ", pageParam);
      getPage(pageParam).then(response => {
        if (response.data.code == 0) {
          console.log("user getPage response: ", response);
          this.currentPageNum = parseInt(response.data.data.current);
          this.userData = response.data.data.records;
          // 在userData的每一项都新增科目名称数组,将科目编号数组的元素逐个转化成科室名字
          this.userData.forEach(person => {
            person.departmentName = [];
            person.department.forEach(dept => {
              person.departmentName.push(this.departmentDict[dept] + " ");
            });
            person.jobTitleName = this.jobTitleDict[person.jobTitle];
            person.userTypeName = [];
            person.userType.forEach(item => {
              person.userTypeName.push(this.roleDict[item] + " ");
            });
          });

          this.totalRecord = parseInt(response.data.data.total);
          console.log("user after getPage: ", this.userData);
        } else {
          console.log("user getPage ERROR!!");
        }
      });
    },
    loadRoles() {
      this.roles = [];
      getAllRole().then(response => {
        if (response.data.code == 0) {
          response.data.data.forEach(item => {
            this.roles.push({ value: item.id, label: item.name });
            this.roleDict[item.id] = item.name;
            // 同理,强制载入
            this.loadPageData();
          });
        } else {
          console.log("getRole ERROR!!");
        }
      });
      // todo:添加api后记得删除
      // this.roles = [
      //   { value: 1, label: "挂号收费员" },
      //   { value: 2, label: "门诊医生" },
      //   { value: 3, label: "医技医生" },
      //   { value: 4, label: "药方操作员" },
      //   { value: 5, label: "财务管理员" },
      //   { value: 6, label: "医院管理员" }
      // ];
    },
    save() {
      this.addDialogVisible = false;

      // todo: 就是接下来的的工作是要保证之前的选项都被选择了
      // 分离参数
      this.user.department = [];
      this.tmpDepartments.forEach(item => {
        this.user.department.push(item[0]);
      });
      this.user.userType = [];
      this.tmpRoles.forEach(item => {
        this.user.userType.push(item[0]);
      });

      this.user.jobTitle = this.user.jobTitle;

      let InsertParam = {
        department: this.user.department,
        id: this.user.id,
        jobTitle: this.user.jobTitle,
        name: this.user.name,
        onDuty: this.user.onDuty,
        password: this.user.passWord,
        username: this.user.userName,
        userType: this.user.userType
      };
      if (this.updateFlag) {
        /* update */
        console.log("send update:", InsertParam);
        update(InsertParam).then(response => {
          if (response.data.code == 0) {
            this.$message("修改成功");
            this.loadPageData();
          } else {
            this.$message.error("修改失败");
          }
        });
      } else {
        /* insert */
        console.log("send insert:", InsertParam);
        insert(InsertParam).then(response => {
          if (response.data.code == 0) {
            this.$message("添加成功");
            this.loadPageData();
          } else {
            this.$message.error("添加失败");
          }
        });
      }
    },
    handleEdit(index, row) {
      this.dialogTitle = "修改";
      // 切记此处不可直接赋值,直接赋值的话传递的是引用,先修改再新建的话,就会影响到之前被修改的行
      this.user = JSON.parse(JSON.stringify(row));
      this.addDialogVisible = true;
      this.updateFlag = true;
    },
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除此项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          /*todo: 在这里填写在数据库中删除的语句 */
          let deleteParam = { ids: [row.id] };
          console.log("send deleteElem:", deleteParam);
          deleteElem(deleteParam).then(response => {
            if (response.data.code == 0) {
              this.$message("删除成功");
              this.loadPageData();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      // 更新页数
      this.loadPageData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPageNum = val;
      // 更新页数
      this.loadPageData();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    },
    batchRemoveButtonClicked() {
      this.$confirm("此操作将永久删除选中项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          /* 先封装成数组,再删除 */
          let removeIds = [];
          this.multipleSelection.forEach(item => {
            removeIds.push(item.id);
          });
          let deleteParam = {
            ids: removeIds
          };
          console.log("send deleteElem:", deleteParam);
          deleteElem(deleteParam).then(response => {
            if (response.data.code == 0) {
              this.$message("删除成功");
              this.loadPageData();
            } else {
              var failedids = "[";
              response.data.data.ids.forEach(item => {
                failedids += item + ",";
              });
              failedids += "]";
              response.data.data.ids;
              this.$message.error("删除 " + failedids + " 失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    queryButtonClicked() {
      this.queryDialogVisible = true;
    },
    queryConfirm() {
      this.queryDialogVisible = false;
      this.currentPageNum = 1;
      this.loadPageData();
    },
    queryResetButtonClicked() {
      /* 补全信息 */
      this.userQuery.id = "";
      this.userQuery.userName = "";
      this.userQuery.passWord = "";
      this.userQuery.name = "";
      this.userQuery.department = [];
      this.userQuery.userType = [];
      this.userQuery.jobTitle = "";
      this.userQuery.onDuty = "";

      // 清空临时变量
      this.tmpQueryDepartments = [];
      this.tmpQueryRoles = [];

      this.loadPageData();
    }
  }
};
</script>

<style>
</style>